package com.example.infowall02.controller;

import com.example.infowall02.domain.Articles;
import com.example.infowall02.utils.AliOssUtil;
import com.example.infowall02.utils.Result;
import com.example.infowall02.service.ArticlesService;
import io.jsonwebtoken.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/article")
public class ArticlesController {

    @Autowired
    private ArticlesService articlesService;
    //自动装配阿里云oss工具类
    @Autowired
    private AliOssUtil aliOssUtil;

//增
    // 添加文章
    @PostMapping
    public Result addArticle(@RequestParam("article.type") String type,
                             @RequestParam("article.theme") String theme,
                             @RequestParam("article.rule") String rule,
                             @RequestParam("article.date") String date,
                             @RequestParam("article.location") String location,
                             @RequestParam("article.signMethod") String signMethod,
                             @RequestParam("article.origin") String origin,
                             @RequestParam("article.content") String content,
                             @RequestParam("image") MultipartFile file) {
        //上传文件到阿里云oss
        log.info("文件上传："+file);

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取文件名后缀  xxx.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName =  UUID.randomUUID().toString() + extension;
            //返回文件请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);

            Articles article = new Articles();
            article.setType(type);
            article.setTheme(theme);
            article.setRule(rule);
            article.setDate(date);
            article.setLocation(location);
            article.setSignMethod(signMethod);
            article.setOrigin(origin);
            article.setContent(content);
            article.setImage(filePath);

            Articles savedArticle = articlesService.addArticle(article);
            if (savedArticle != null) {
                return Result.success(savedArticle);
            }
            return Result.error("添加失败");
        } catch (IOException e) {
            log.warn("文件上传失败");
            e.printStackTrace();
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
        return Result.error("文件上传失败");
    }

//删
    // 根据文章 ID 删除文章
    @DeleteMapping("/{id}")
    public Result deleteArticleById(@PathVariable int id) {
        boolean isDeleted = articlesService.deleteArticleById(id);
        if (isDeleted) {
            return Result.success("删除文章成功");
        } else {
            return Result.error("删除文章失败，可能文章不存在");
        }
    }

//查
    // 根据文章 ID 查找文章
    @GetMapping("/{id}")
    public Result<Articles> findArticleById(@PathVariable int id) {
        Articles article = articlesService.findArticleById(id);
        if (article != null) {
            //每次被id查询，则增加点击量
            articlesService.incrementClicks(id);
            return Result.success(article);
        } else {
            return Result.error("未找到该文章");
        }
    }
    // 根据文章类别查找文章
    @GetMapping("/type/{type}")
    public Result<Map<String, Object>> findArticleByType(@PathVariable String type,
                                                    @RequestParam int pageNow,
                                                    @RequestParam int pageSize){
        int totalCount = articlesService.countArticlesByType(type);
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);
        // 确保总页数至少为 1
        totalPages = Math.max(totalPages, 1);
        // 确保起始索引不超过总记录数,并且不小于1
        pageNow = Math.max(pageNow, 1);
        pageNow = Math.min(pageNow, totalPages);
        // 计算起始索引
        pageNow = (pageNow-1)*pageSize;
        // 调用服务层方法
        List<Articles> articles = articlesService.findArticlesByType(type, pageNow, pageSize);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("articles", articles);
        resultMap.put("totalPages", totalPages);
        if (!articles.isEmpty()) {
            return Result.success(resultMap);
        } else {
            return Result.error("未找到该类别的文章");
        }
    }
    // 根据文章标题或类别模糊查找文章
    @GetMapping("/search")
    public Result<Map<String, Object>> findArticlesByKeyword(@RequestParam String keyword,
                                                             @RequestParam int pageNow,
                                                             @RequestParam int pageSize) {

        int totalCount = articlesService.countArticlesByKeyword(keyword);
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);
        // 确保总页数至少为 1
        totalPages = Math.max(totalPages, 1);
        // 确保起始索引不超过总记录数,并且不小于1
        pageNow = Math.max(pageNow, 1);
        pageNow = Math.min(pageNow, totalPages);
        // 计算起始索引
        pageNow = (pageNow-1)*pageSize;
        // 调用服务层方法
        List<Articles> articles = articlesService.findArticlesByKeyword(keyword,pageNow,pageSize);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("articles", articles);
        resultMap.put("totalPages", totalPages);
        if (!articles.isEmpty()) {
            return Result.success(resultMap);
        } else {
            return Result.error("未找到符合条件的文章");
        }
    }
    // 按时间顺序推荐文章
    @GetMapping("/recommend/time")
    public Result<List<Articles>> findArticlesByTime() {
        List<Articles> articles = articlesService.findRecommendArticlesByTime();
        if (!articles.isEmpty()) {
            return Result.success(articles);
        }
        return Result.error("未找到推荐文章");
    }
    // 按点击量推荐文章
    @GetMapping("/recommend/clicks")
    public Result<List<Articles>> findArticlesByClicks() {
        List<Articles> articles = articlesService.findRecommendArticlesByClicks();
        if (!articles.isEmpty()) {
            return Result.success(articles);
        }
        return Result.error("未找到推荐文章");
    }
//改
    // 增加点赞数
    @PutMapping("/{id}/likes")
    public int incrementLikes(@PathVariable int id) {
        return articlesService.incrementLikes(id);
    }

    // 增加点击量
    @PutMapping("/{id}/clicks")
    public int incrementClicks(@PathVariable int id) {
        return articlesService.incrementClicks(id);
    }

    // 增加收藏数
    @PutMapping("/{id}/favorites")
    public int incrementFavorites(@PathVariable int id) {
        return articlesService.incrementFavorites(id);
    }

    // 修改除了 id、点赞、点击、收藏数的信息
    @PutMapping("/{id}")
    public Result updateArticleInfo(@PathVariable int id,
                                    @RequestParam("article.type") String type,
                                    @RequestParam("article.theme") String theme,
                                    @RequestParam("article.rule") String rule,
                                    @RequestParam("article.date") String date,
                                    @RequestParam("article.location") String location,
                                    @RequestParam("article.signMethod") String signMethod,
                                    @RequestParam("article.origin") String origin,
                                    @RequestParam("article.content") String content,
                                    @RequestParam("image") MultipartFile file) {
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取文件名后缀  xxx.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName =  UUID.randomUUID().toString() + extension;
            //返回文件请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);

            Articles article = new Articles();
            article.setType(type);
            article.setTheme(theme);
            article.setRule(rule);
            article.setDate(date);
            article.setLocation(location);
            article.setSignMethod(signMethod);
            article.setOrigin(origin);
            article.setContent(content);
            article.setImage(filePath);

            boolean isUpdated = articlesService.updateArticleInfo(article,id);
            if (isUpdated) {
                return Result.success(article);
            } else {
                return Result.error("文章信息更新失败");
            }
        } catch (IOException e) {
            log.warn("文件上传失败");
            e.printStackTrace();
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
        return Result.error("文件上传失败");
    }
}
